package com.bblocks.common.jsonfields;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.bblocks.common.jsonfields.constant.FieldsConstants;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.bohnman.squiggly.Squiggly;
import com.github.bohnman.squiggly.util.SquigglyUtils;
import com.google.common.base.Joiner;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


/**
 * <p>Project: bblocks-pro - ResponseFieldFilterAdvice</p>
 * <p>描述：json字段</p>
 *
 * @Author Zhao [125043150@qq.com]
 * @Date 2024/2/18 15:10
 * @Version 1.0
 * @since 8
 */
@Slf4j
@ControllerAdvice
public class ResponseFieldFilterAdvice implements ResponseBodyAdvice {

    @Resource
    private ObjectMapper objectMapper;

    private static final String FIELDS_QUERY_PARAM = "fields";



    @Override
    public boolean supports(final MethodParameter methodParameter, final Class converter) {
        return true;
    }


    @Override
    public Object beforeBodyWrite(final Object body, final MethodParameter methodParameter, final MediaType mediaType, final Class selectedConverter, final ServerHttpRequest serverHttpRequest, final ServerHttpResponse serverHttpResponse) {
       if (body instanceof com.bblocks.util.R){
            String filter = fieldParamsFilter(serverHttpRequest);
            if(StrUtil.isNotEmpty(filter)){
                if(log.isDebugEnabled())
                    log.info("过滤字段:{}",filter);
                //ObjectMapper objectMapper = Squiggly.init(new ObjectMapper(), filter);
                ObjectMapper objectMapperField = Squiggly.init(objectMapper.copy(), filter);

                com.bblocks.util.R<Object> rbody = (com.bblocks.util.R<Object>)body;
                if(rbody.getData() != null){
                    Object dataAfter = SquigglyUtils.objectify(objectMapperField, rbody.getData(), rbody.getData().getClass());
                    rbody.setData(dataAfter);
                }
                objectMapperField = null;
            }
        }else if(body instanceof com.pig4cloud.pig.common.core.util.R){
            log.warn("暂未实现！");
        }

        return body;
    }


    /**
     * 获取过滤入参（1、从head提取，2、从入参请求提取）
     * @param serverHttpRequest
     */
    private String fieldParamsFilter(ServerHttpRequest serverHttpRequest){

        String filter = null;
        if(serverHttpRequest.getHeaders().containsKey(FieldsConstants.JSON_FIELDS_PARAM_KEY)){
            filter = serverHttpRequest.getHeaders().get(FieldsConstants.JSON_FIELDS_PARAM_KEY).get(0);
        }else{
            String  queryParamsStr = serverHttpRequest.getURI().getQuery();
            if(StrUtil.isNotEmpty(queryParamsStr)){
                Map<String, List<String>> params = HttpUtil.decodeParams(queryParamsStr, CommonConstants.UTF8);
                List<String> filters = params.get(FieldsConstants.JSON_FIELDS_PARAM_KEY);
                if(CollUtil.isNotEmpty(filters))
                    filter = Joiner.on(",").join(filters);
            }
        }

        return filter;
    }

}
